import axios from '../http/http.js';
import configService from '../service/ConfigService.js';
import utilService from '../service/UtilService.js';

const ignorePath = new Set();

export default {

  //初始化权限
  async initAuthority() {
    let authCode = this.getAuthCode();
    if (!authCode) {
      this.toLoginPage();
    } else {
      let authority = await this.loadAuthority(authCode)
      if (authority) {
        utilService.addSessionParameter("authority", authority)
        utilService.addSessionParameter("code", authCode)
        console.log("权限初始化完毕！")
      } else {
        this.toLoginPage();
      }
    }
  },
  getAuthCode() {
    let queryToJson = utilService.queryToJson(window.location.search);
    if (queryToJson && queryToJson.code) {
      return queryToJson.code;
    }
    return utilService.getSessionParameter("code");
  },
  getCode() {
    return utilService.getSessionParameter("code");
  },
  async loadAuthority(code) {
    return await axios.post(configService.ssoAuthViewPath, {
      app: configService.app,
      code: code
    })
  },
  toLoginPage() {
    window.location.href = configService.ssoPage + "?to=" + utilService.changeUrlArg(window.location.href, "code", "").replace("code=", "")
  },

  checkAuthority: function (code) {
    let resourcesLocators = utilService.getSessionParameter("authority").resourcesCodes;
    if (resourcesLocators.indexOf(code) > -1 || ignorePath.has(code)) {
      return true;
    }
    return false;
  },

  addIgnorePath(name) {
    ignorePath.add(name)
  },

  subject() {
    return utilService.getSessionParameter("authority").ssoUserView;
  },

  resourceTree() {
    return utilService.getSessionParameter("authority").resourceTreeViews;
  },

  logout() {
    axios.get(configService.logout).then(data => {
      this.toLoginPage();
    })
  }

}

